// app.js
App({
  onLaunch() {
    this.globalData.token = wx.getStorageSync('token');
    this.globalData.userInfo = wx.getStorageSync('userInfo');
    this.globalData.openId = wx.getStorageSync('openId');
    this.isCode();
  },
  isCode() {
    wx.request({
      url: this.globalData.baseUrl + "/api/applet/product/getList",
      method: "GET",
      header: {
        'Content-Type': 'application/json ',
        Authorization: `Bearer ${this.globalData.token}`
      },
      success: (res => {
        if (res.data.code === 10) {
          this.initCode()
        }
      })
    })
  },
  initCode() {
    wx.login({
      success: async loginRes => {
        try {
          wx.request({
            url: this.globalData.baseUrl + "/api/applet/code",
            method: "GET",
            data: {
              code: loginRes.code,
              type: 1,
            },
            success: (res => {
              const {
                code,
                data
              } = res.data;
              console.log(code, "data", data);
              this.globalData.openId = data.openId;
              wx.setStorageSync('openId', data.openId);
              this.globalData.ifLogin = true;
              this.globalData.userId = data.userId;
              wx.setStorageSync('userInfo', data);
              if (data.phone) {
                console.log(data.token, "token");
                this.globalData.token = data.token;
                this.globalData.ifLogin = true;
                wx.setStorageSync('token', data.token);
                console.log(wx.getStorageSync('token'), "111");
              }
            })
          })
        } catch (err) {
          console.log(err, "getCode error");
        }
      },
      fail(error) {
        console.log(error, "login fail");
      },
    });
  },
  globalData: {
    baseUrl: 'https://wudifenghuolun.yqjjt.com', // 开发环境
    sessionKey: '', //默认sessionKey信息
    openId: '', //默认openId信息
    token: '', //登录token
    userInfo: '', //统一存用户信息：phoneNumber、purePhoneNumber、countryCode、appid
    ifLogin: false, //登录与否
    userId: '', //获取手机号时需要的userId
    nowPages: 0,
  },
})